package com.bsoft.gol.editor.fileUpload;


import com.bsoft.gol.editor.dao.EditorOrganizationDAO;
import com.bsoft.gol.editor.dao.EditorUserDAO;
import com.bsoft.gol.editor.editor.EditorOrganization;
import com.bsoft.gol.editor.editor.EditorUser;
import com.bsoft.gol.editor.utils.CommonUtils;

import java.util.List;
import java.util.concurrent.CountDownLatch;


public class UserDataImportTask implements Runnable{

	public UserDataImportTask(CountDownLatch countDownLatch, EditorUserDAO editorUserDAO,EditorOrganizationDAO editorOrganizationDAO, TableData<UserHolder> tableData){
		this.countDownLatch = countDownLatch;
		this.tableData = tableData;
		this.editorUserDAO = editorUserDAO;
		this.editorOrganizationDAO = editorOrganizationDAO;
	}

	public UserDataImportTask(CountDownLatch countDownLatch, EditorUserDAO editorUserDAO,EditorOrganizationDAO editorOrganizationDAO, TableData<UserHolder> tableData, int start, int end){
		this.countDownLatch = countDownLatch;
		this.tableData = tableData;
		this.editorUserDAO = editorUserDAO;
		this.editorOrganizationDAO = editorOrganizationDAO;
		this.start = start;
		this.end = end;
	}
	
	private CountDownLatch countDownLatch;
	private EditorUserDAO editorUserDAO;
	private EditorOrganizationDAO editorOrganizationDAO;

	private TableData<UserHolder> tableData;
	private int start = 0;//开始处理的行
	private int end = Integer.MAX_VALUE;//结束处理的行

	@Override
	public void run() {
		List<UserHolder> rows = tableData.getRowData();
		if (start < 0) {
			start = 0;
		}
		if (end > rows.size()) {
			end = rows.size();
		}
		for (int j = start; j < end; j++) {
			UserHolder holder = rows.get(j);
			if (!holder.isValid()) {
				continue;
			}
			try {

				if(CommonUtils.isNotEmpty(holder.getEditorUser().getLoginName())){
					List<EditorUser>  editorUser= editorUserDAO.queryEditorUserByLoginName(holder.getEditorUser().getLoginName());
					if (null != editorUser&&editorUser.size()!=0) {
						holder.setValid(false);
						holder.append(ErrorTipConst.SPLIT_CHAR);
						holder.append("登录名被占用");
					}
				}

				if(CommonUtils.isNotEmpty(holder.getEditorUser().getOrgId())){
					EditorOrganization editorOrganization=editorOrganizationDAO.getEditorOrganizationById(holder.getEditorUser().getOrgId());
					if(CommonUtils.isNull(editorOrganization)){
						holder.setValid(false);
						holder.append(ErrorTipConst.SPLIT_CHAR);
						holder.append("机构id不存在");
					}
				}

				if (holder.isValid()) {
					editorUserDAO.save(holder.getEditorUser());
				}

			} catch (Exception e) {
				holder.setValid(false);
				holder.append(e.getMessage());
				e.printStackTrace();
			}

			if (!holder.isValid()) {
				tableData.addInvalidCount();
			}
		}
		if (countDownLatch != null) {
			countDownLatch.countDown();
		}
	}
}
